﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using nanoCMS.Core.Membership;
using nanoCMS.Core.Resources;
using nanoCMS.Core.WebProviders;
using nanoCMS.Core.WebUI.Models;
using nanoCMS.Core.WebUI.Models.ViewModels;
using nanoCMS.Core.Extensions;

namespace nanoCMS.Core.WebUI.Controllers {
	public class UserController : Controller {
		private WorldContext worldContext;
		private UserService userService;

		public UserController(WorldContext worldContext) {
			this.worldContext = worldContext;
			userService = new UserService(worldContext);
		}

		[HttpGet]
		public ActionResult Register() {
			var model = new UserRegisterVM();
			return PartialView("Register", model);
		}

		[HttpPost]
		public ActionResult Register(UserRegisterVM model) {
			if (ModelState.IsValid) {
				MembershipReturn status = userService.RegisterUser(model);
				if (status == MembershipReturn.Success)
					return this.Content("OK");
				else if (status == MembershipReturn.EmailInUse)
					ModelState.AddModelError("Email", TranslationMessages.EmailInUse);
			}

			return PartialView("ValidationSummary");
		}

		[HttpGet]
		public ActionResult LogOut(string returnUrl) {
			userService.LogOut();
			if (String.IsNullOrEmpty(returnUrl)) {
				return this.Content("OK");
			}
			return Redirect(System.Web.HttpUtility.UrlDecode(returnUrl));
		}


		[HttpGet]
		public ActionResult LogInPage()
		{
			return Content("Show login :D");
		}

		[HttpGet]
		public ActionResult Login() {

			return PartialView("Login");
		}

		[HttpPost]
		public ActionResult Login(UserLogOn model) {
			if (ModelState.IsValid) {
				if (userService.LogIn(model))
					return Json(new { status = "reload" }, JsonRequestBehavior.AllowGet);
				ModelState.AddModelError("", TranslationMessages.WrongEmailOrPassword);
			}
			return PartialView("ValidationSummary");
		}

		[HttpGet]
		[NcAuthorize]
		public ActionResult Edit() {
			return PartialView("EditUser", userService.BuildEditModel());
		}

		[HttpPost]
		public ActionResult Edit(UserVM userVM, PasswordVM passwordVM) {
			// check password
			if (userService.IsPasswordInserted(passwordVM)) {
				if (!userService.CheckPasswordMatch(passwordVM)) {
					// TODO hardcoded string
					ModelState.AddModelError("Password", "Error in password/password confirm match!");
				}
				if (!userService.CheckOldPassword(passwordVM)) {
					ModelState.AddModelError("Password", "Old password don't confirm!");
				}
			}
			// check disply name
			if (string.IsNullOrEmpty(userVM.DisplayName)) {
				ModelState.AddModelError("DisplayName", "Display name required!");
			}
			if (ModelState.IsValid) {
				bool success = userService.EditUser(userVM, passwordVM);
				if (success) {
					return Content("Profile saved!"); // TODO
				}
			}
			return PartialView("ValidationSummary");
		}

		[HttpPost]
		public ActionResult UploadAvatar(int? chunk, string name, string type) {
			try {
				if (!chunk.HasValue) {
					HttpPostedFileBase uploadedFile = Request.Files[0];
					// check uploaded file
					if (uploadedFile == null) {
						throw new Exception("Error during upload.");
					}
					// get avatar settings
					int avatarW = Convert.ToInt32(Settings.AvatarWidth);
					int avatarH = Convert.ToInt32(Settings.AvatarHeight);
					// process image
					Image image = Image.FromStream(uploadedFile.InputStream);
					// resize if necessary
					if (image.Width > avatarW || image.Height > avatarH) {
						image = image.Resize(avatarW, avatarH);
					}
					// store image to disk
					string imageDestination = Server.MapPath(Settings.AvatarUploadPath);
					string newFileName = AvatarProvider.GenerateAvatarName(SessionManagerBase.CurrentUserID);
					string uploadPath = Path.Combine(imageDestination, newFileName);
					image.Save(uploadPath, ImageFormat.Png);
					//                    using (var fs = new FileStream(uploadPath, FileMode.Create))
					//                    {
					//                        // read into buffer
					//                        byte[] buffer = new byte[uploadedFile.InputStream.Length];
					//                        uploadedFile.InputStream.Read(buffer, 0, buffer.Length);
					//                        // write to location 
					//                        fs.Write(buffer, 0, buffer.Length);
					//                    }
					string returnFileName = newFileName + "?newGuid=" + Guid.NewGuid();
					var result = new { result = "ok", fileName = returnFileName };
					return Json(result);
				} else {
					throw new Exception("Chunking not supported!");
				}
			} catch (Exception e) {
				return Json(new { result = "error", message = e.Message });
			}
		}

		[HttpPost]
		public ActionResult DeleteAvatar() {
			try {
				string directory = Server.MapPath(Settings.AvatarUploadPath);
				string fileName = AvatarProvider.GenerateAvatarName(SessionManagerBase.CurrentUserID);
				//write chunk to disk.  
				string avatarPath = null;
				if (Path.IsPathRooted(directory)) {
					avatarPath = Path.Combine(directory, fileName);
				} else {
					avatarPath = Path.Combine(Server.MapPath(directory), fileName);
				}
				if (System.IO.File.Exists(avatarPath)) {
					System.IO.File.Delete(avatarPath);
					var result = new { result = "ok", fileName };
					return Json(result);
				} else {
					throw new Exception("Could not delete avatar!");
				}
			} catch (Exception e) {
				return Json(new { result = "error", message = e.Message });
			}
		}
	}
}
